export default {
	name: "rowform",
	setup(props, { emit }) {
		const router = VueRouter.useRouter();
		const route = VueRouter.useRoute();
		const { smartSpeak } = inject('speech'); //语音
		const lastpage = ref();
		const formRef = ref(null);
		const formData = reactive({reservation_date: '',slot_start: '',slot_end: ''});
		const formRules = reactive({});
		const tableid = ref();//项目id
		const rowid = ref(); //行id
		const option = ref({url: '', name: 'file'});
		const jsonkeys = ref(['muselect', 'checkbox', 'multiimage', 'subtable', 'multifile', 'video', 'area']);
		const bgsx = ref();
		const columns = ref({});
		const ldoptions = ref({});//联动下拉options
		const availableDates = ref([]);
        const availableSlots = ref([]);
        const originalUser = ref({});
        const showUploadDialog = ref({});
        const isbutton = ref(false);
        const dialogmap = ref(false);
        
		const handleQueryNotFound = (msg) => {
		    smartSpeak(msg);
			ElMessage.error(msg);
            if (!bgsx.value.jzfh) {
				setTimeout(() => {
					 router.push({name: 'home'});
				}, 600);
			}
		}
		
		// 字段处理器
		const fieldProcessor = {
			// 处理下拉选项
			splitPathToOptions(path) {
				if (typeof path !== 'string') return [];
				return path.split('/').filter(Boolean).map(v => ({ value: v.trim(), label: v.trim() }));
			},
			// 处理字段配置
			process(fields) {
				if (!fields) return null;
				return Object.entries(fields).map(([prop, field]) => field && {
					...field,
					prop,
					label: field.name,
					width: field.width || undefined,
					options: ['select', 'muselect', 'radio', 'checkbox'].includes(field.type) && field.options ? this.splitPathToOptions(field.options) : field.options,
				}).filter(Boolean)
			},
			// 统一数据初始化
			initFormData(fields, rowData = null) {
				fields.forEach(field => {
					// 如果已有数据则跳过（保留用户输入）
					if (formData[field.prop] !== undefined) return
					// 优先使用行数据
					let value = rowData?.[field.prop]
					// 处理需要JSON解析的字段
					if (jsonkeys.value.includes(field.type)) {
						value = this.parseJSON(value)
					}
					formData[field.prop] = value ?? getDefaultValue(field)
				})
			},
			// JSON数据处理
			parseJSON(value) {
				try {
					return window.validators.isJSON(value) ? JSON.parse(value) : undefined
				} catch {
					return undefined
				}
			}
		}
		
		// 获取组件属性
        const getpath = () => {
            return (bgsx.value?.formname || '').replace(/[\\/:*?"<>|\s]/g, '');
        }
        const getComponentProps = (field) => createGetComponentProps({
            getDisabled: (field) => !bgsx.value.kftb || !bgsx.value.kftb.includes(field.prop),
            getUploadImgwh: (field) => bgsx.value?.fields?.[field.prop]?.options || '',
            getUploadPath: () => getpath(),
            getRichtextPath: () => getpath()
        })(field, formData);
		
		// 提交表单
		const submitForm = _.debounce(async() => {
		    const user = JSON.parse(localStorage.getItem('user'));
			await formRef.value.validate();
			const processedData = processFormData(formData);
			//检查预约表单项
			if (bgsx.value.id && bgsx.value.isReservation) {
				const requiredFields = [
					{ field: 'reservation_date', name: '预约日期' },
					{ field: 'slot_start', name: '开始时间' },
					{ field: 'slot_end', name: '结束时间' }
				]
				// 遍历检查每个必填项
				for (let item of requiredFields) {
					if (!processedData[item.field]?.trim()) {
					    return ElMessage.error(`${item.name}不得为空`);
					}
				}
			}else{
			    // 非预约模式主动移除字段（双重保障）
				const reservationFields = ['reservation_date', 'slot_start', 'slot_end'];
				reservationFields.forEach(field => {
					delete processedData[field] // 彻底移除字段
				})
			}
			let input = { ...lastpage.value };
			let data = {
                tid: rowid.value || 0,
                id: bgsx.value.id,
                userid: Number(user?.ID) || 0,
                row: processedData,
                input: input
            }
            isbutton.value = true;
            //预约、审核和普通表单
    	    const res = bgsx.value.processConfig?.length || bgsx.value.isReservation ? await addtablerow(data) : await qdeditrow(data);
            // 流程表单不跳转
            if (bgsx.value.processConfig?.length) {
                ElMessage.success('提交成功');
                router.go(-1);
                return;
            }
            // 统一跳转到结果页
            router.push({
                name: 'submitResult',
                query: {
                    type: bgsx.value.isReservation ? 'reservation' : 'normal',
                    code: res.verification_code || '',
                    date: formData.reservation_date || '',
                    start: formData.slot_start || '',
                    end: formData.slot_end || '',
                    sequence: res.sequence_number || 0,
                    formName: encodeURIComponent(bgsx.value.formname),
                    submitTime: new Date().toISOString()
                }
            });
		}, 500);
		
        // 提交数据处理
        const processFormData = (rawData) => {
            const user = JSON.parse(localStorage.getItem('user'));
			const data = { ...rawData }
			columns.value.forEach(field => {
				if (jsonkeys.value.includes(field.type)) {
					if (Array.isArray(data[field.prop])) {
						data[field.prop] = JSON.stringify(data[field.prop]); //防止json转换乱
					}
				}
				// 处理身份证号去除空格
				if (field.type === 'idcard') {
					data[field.prop] = data[field.prop]?.replace(/\s/g, '')
				}
				// 处理数字类型转换
				if (field.type === 'number') {
					data[field.prop] = data[field.prop]?.toString() || '';
				}
				if (field.type == 'date' && field.prop == 'reservation_date' && data.reservation_date) {
                    data.reservation_date =  window.validators.formatDate(data.reservation_date, 'YYYY-MM-DD');//预约日期强制转字符
                }
				data[field.prop] = data[field.prop] || ''; //防止空值undefined不更新
			})
			if(!data['cjz'] || data['cjz'] == 0) data['cjz'] = Number(user?.ID) || 0;
			return data
		}
		
		// 身份证识别功能
		const scanIdCard = _.debounce(async(fieldKey) => {
			try {
				const input = document.createElement('input')
				input.type = 'file'
				input.accept = 'image/*'
				input.onchange = async (e) => {
					const file = e.target.files[0];
					if (file) {
						const formData = new FormData();
						formData.append('file', file);
						const res = await axios.post('/v1/uploadsfz', formData);
						handleIdCardResult(res.data?.result?.words_result, fieldKey);
					}
				}
				input.click();
			} catch (err) {
				ElMessage.error('身份证识别失败')
				smartSpeak('身份证识别失败')
			}
		}, 200);
		
		// 身份证自动填充逻辑
		const handleIdCardResult = (data, fieldKey) => {
		    if(!data) return;
			const fieldConfig = columns.value.find(f => f.prop === fieldKey)
			if (!fieldConfig?.sfzoptions) return
			const mapping = {
				'公民身份号码': fieldKey,
				'姓名': fieldConfig.sfzoptions.name,
				'性别': fieldConfig.sfzoptions.sex,
				'民族': fieldConfig.sfzoptions.mz,
				'出生': fieldConfig.sfzoptions.day,
				'住址': fieldConfig.sfzoptions.ade
			}
			Object.entries(mapping).forEach(([srcKey, targetKey]) => {
				if (targetKey && data[srcKey]) {
					formData[targetKey] = data[srcKey].words.toString();
				}
			})
			if(formData[fieldKey]) handleIdCardInput(formData[fieldKey], fieldKey)
		}
	
		// 身份证输入处理
		const handleIdCardInput = (value, fieldKey) => {
			if (value.length === 18) {
				const info = extractIdCardInfo(value)
				const fieldConfig = columns.value.find(f => f.prop === fieldKey)
				// 自动填充关联字段
				if (fieldConfig?.sfzoptions) {
					nextTick(() => {
						if (fieldConfig.sfzoptions.sex) {
							formData[fieldConfig.sfzoptions.sex] = info.gender
						}
						if (fieldConfig.sfzoptions.day) {
							formData[fieldConfig.sfzoptions.day] = info.birthdate
						}
						if (fieldConfig.sfzoptions.old) {
                        	formData[fieldConfig.sfzoptions.old] = info.old
                        }
					})
				}
			}
		}
		
		const handleBeforeUpload = (file, field) => {
			const isImage = file.type.startsWith('image/')
			if (!isImage) {
				ElMessage.error('只能上传图片文件')
				smartSpeak('只能上传图片文件')
				return false
			}
			if (['image', 'sczs'].includes(field.type) && formData[field.prop]?.length >= 1) {
				ElMessage.error('只能上传一张图片')
				smartSpeak('只能上传一张图片')
				return false
			}
			return true
		}
	
        // 图片附件上传处理
        const handleUploadSuccess = (response, field) => {
            if (!response.data) return
            const url = response.data
            if (['image', 'sczs', 'file'].includes(field.type)) {
                formData[field.prop] = url;
            } else {
                if (!Array.isArray(formData[field.prop])) {
                	formData[field.prop] = [];
                }
                formData[field.prop].push(url);
        	}
        }
		
    	// 处理文件删除
    	const handleRemove = (file, field) => {
            if (['image', 'sczs', 'file'].includes(field.type)) {
            	formData[field.prop] = '';
            } else if(field.type == 'multifile'){
                formData[field.prop].splice(file, 1); //file为index
            } else {
            	const index = formData[field.prop].findIndex(url => url === file.url)
            	if (index > -1) {
            		formData[field.prop].splice(index, 1)
            	}
            }
        }
		
		// 文件列表转换器
		const getFileList = (field) => {
			return computed(() => {
				const value = formData?.[field.prop]
				if (['image', 'sczs'].includes(field.type)) {
					return value ? [{uid: '-1', name: field.prop, url: value, status: 'success' }] : [];
				}
				return value?.map(url => ({ name: field.prop, url })) || [];
			}).value;
		}
		
		const getFieldType = (prop) => {
			const field = columns.value.find(f => f.prop === prop)
			return field?.type || 'text'
		}
		
		//子表添加一行
		const addRow = (key, options) => {
			if (typeof key !== 'string' || !Array.isArray(options) || options.length == 0) {
				return;
			}
			let obj = {};
			for (let v of options) {
				obj[v.key] = '';
			}
			if (!Array.isArray(formData[key])) {
				formData[key] = [obj];
			}else{
				formData[key].push(obj);
			}
		}
		
		//子表删除一行
		const DeleteZd = (index, key) => {
			formData[key].splice(index, 1);
		}
		
		const toback = () => {
			router.push({name: 'home'});
		}

        //联动下拉 visible-change下拉框出现/隐藏时触发
        const handleVisibleChange = async (visible, key) => {
            if (visible) {
                let id = bgsx.value.fields[key].kbtable;//联动表项目id
                let fh = bgsx.value.fields[key].kbcxcol;//返回列
                let max = Number(bgsx.value.fields[key].kbcxz);//总级数
                let now = Number(bgsx.value.fields[key].kbfhcol);//当前级
                if(id && fh && max > 1 && now && now <= max){
                    let values = {};//共支持5级下拉，如查第5级，需要传递1234级的key=>value
                    //遍历联动字段，查找联动级
                    const ldkeys = Object.keys(bgsx.value.fields).filter(key => bgsx.value.fields[key].type === 'linkselect');
                    for(let k of ldkeys) {
                        //不是最后一级时，要获取下级选项
                        if(bgsx.value.fields[k].kbfhcol < now) {
                            if(!formData[k]){
                                values = {};
                                break;//如果上级有空值，则禁止返回下级选项
                            }
                            let tempkey = bgsx.value.fields[k].kbcxcol;   //联动表中的查询列
                            values[tempkey] = formData[k];       //生成查询关联数组
                        }
                    }
                    //如果是第一级，或者有查询关联数组时，后端获取选项
                    if(now == 1 || Object.values(values).length > 0){
                        ldoptions.value[key] = await getldoptions({id, fh, max, now, values});
                    }
                }
            }
        }
        //联动选项变化，下级要清空
        const lxChange = (key) => {
            let now = Number(bgsx.value.fields[key].kbfhcol);//当前级
            const ldkeys = Object.keys(bgsx.value.fields).filter(key => bgsx.value.fields[key].type === 'linkselect');
            for(let k of ldkeys) {
                if(bgsx.value.fields[k].kbfhcol > now) {
                    console.log(k);
                    formData[k] = '';
                    ldoptions.value[k] = '';
                }
            }
        }
        
		// 预约类表单
		const initReservation = async () => {
			if (!bgsx.value?.id || !bgsx.value.isReservation) return;
			availableDates.value = await GetAvailableDates({formId: bgsx.value.id});
		}

		const selectDate = async (date) => {
			if (date.remaining <= 0 || date.hasBooked) return;
			formData.reservation_date = date.date;
			availableSlots.value = await GetTimeSlots({formId: bgsx.value.id, date: date.date});
			// 清空已选时段
			formData.slot_start = '';
			formData.slot_end = '';
		};

		const selectSlot = (slot) => {
		    console.log(slot)
			if (slot.remaining <= 0) return;
			formData.slot_start = slot.start;
			formData.slot_end = slot.end;
		};

		// 日期分块方法
		const chunkDates = (arr, size) => {
			const chunks = [];
			for (let i = 0; i < arr.length; i += size) {
				chunks.push(arr.slice(i, i + size));
			}
			return chunks;
		};
		
        // 字段可见性判断
        const checkVisibility = (fieldProp) => {
            const conditions = bgsx.value?.fields?.[fieldProp]?.conditions;
            if (!conditions || !conditions.field) return true; // 无配置时显示
            const watchedValue = formData[conditions.field];
            const targetValues = Array.isArray(conditions.value) ? conditions.value : [conditions.value];
            // 判断是否匹配值（任一匹配即可）
            const isMatch = targetValues.some(val => val == watchedValue); // 宽松匹配
            return conditions.action === 'show' ? isMatch : !isMatch;
        };

		onMounted(async() => {
		    ldoptions.value = {};
			if (!route.query.data) {
				smartSpeak('参数不正确，请返回');
				ElMessage.error('参数不正确，请返回');
				setTimeout(() => {
					router.back();
				}, 1500);
			} else {
				lastpage.value = JSON.parse(decodeURIComponent(route.query.data));
				// 路由参数规范化
				[tableid.value, rowid.value] = ['tableid', 'rowid'].map(k =>Number(route.params[k]) || null);
				if (!tableid.value) return
				// 获取元数据
				bgsx.value = await getbgsxapi({id: tableid.value});
				if (!bgsx.value?.fields) return
                //检查是否流程表单和前台显示：1.全开放, 2.登录可见, 3.管理员，4.指定填报员
				if(bgsx.value.processConfig?.length || bgsx.value.isReservation || bgsx.value.qtxs != '全开放'){
					originalUser.value = await getuser();
                    let role = originalUser.value?.Role;
                    if(bgsx.value.qtxs == '管理员' && role != 'admin') {
                    	return ElMessage.error('仅限管理员填报');
                    }else if(bgsx.value.qtxs == '指定填报员') {
                    	if (!['admin', 'xmgly', 'tby'].includes(role) || (role === 'tby' && !bgsx.value.tby.includes(originalUser.value.ID))) {
                            return ElMessage.error('您无权填报该项目');
                    	}
                    }
				}
                if (isTimeValid(bgsx.value.starttime) && isAfterShanghaiTime(bgsx.value.starttime)) {
                    return handleQueryNotFound(`查询未开始！\n 开始时间：${formatDate(bgsx.value.starttime)}`)
                }
                if (isTimeValid(bgsx.value.endtime) && isBeforeShanghaiTime(bgsx.value.endtime)) {
                    return handleQueryNotFound(`查询已结束！\n 结束时间：${formatDate(bgsx.value.endtime)}`)
                }
				// 处理列配置
				columns.value = fieldProcessor.process(bgsx.value.fields)
				// 初始化验证规则
        		for (let k in bgsx.value.fields) {
        			formRules[k] = generateRules(bgsx.value.fields[k], false);
        		}
				// 获取行数据（如果有）
				let input = { ...lastpage.value };
				const row = rowid.value ? (await getformid({bm: bgsx.value.tablename,id: rowid.value,input: input}))[0] || null :null;
				// 统一初始化
				Object.assign(formData, {}) // 清空原有数据
				fieldProcessor.initFormData(columns.value, row)
				if (bgsx.value?.isReservation) {
                    await initReservation();
                }
			}
		});
		
    	//显示地图
        const showMyMap = (string) => {
            if(!string)return;
            dialogmap.value = true;
            setTimeout(() => {
                let array = string.split(',');
                //定义地图中心点坐标
                var center = new TMap.LatLng(array[0],array[1])
                //定义map变量，调用 TMap.Map() 构造函数创建地图
                var map = new TMap.Map(document.getElementById('container'), {
                    center: center,//设置地图中心点坐标
                    zoom: 15,   //设置地图缩放级别
                    pitch: 43.5,  //设置俯仰角
                    rotation: 45    //设置地图旋转角度
                });
                //标记中心点
                var markerLayer = new TMap.MultiMarker({
                    map: map,
                    geometries: [{"id": "1","position": center}]
                });
            }, 500);
        }
		
        // 行内计算和拼接
        watch(() => formData, (newVal) => {
            calculateFields(newVal, bgsx.value?.fields);
        }, { deep: true });

		return {
		    originalUser, getLocation, showMyMap, dialogmap, parsedValue,
            handleVisibleChange,
            lxChange,
            ldoptions,
			bgsx,
			formRules,
			getComponentProps,getpath,
			processFormData,
			scanIdCard,
			handleIdCardInput,
			extractIdCardInfo,
			handleBeforeUpload,
			handleUploadSuccess,
			handleRemove,
			getFileList,
			getFieldType,
			columns,
			addRow,
			DeleteZd,
			submitForm,
			formData,
			handleQueryNotFound,
			datelx,
			formRef,
			toback,
			lastpage,
            availableDates,
            availableSlots,
            chunkDates,
            selectDate, isbutton,
            selectSlot, showUploadDialog, getFileName,checkVisibility,
            regionData: elementChinaAreaData.regionData,
		}
		
	},
	
	template: `
<el-dialog v-model="dialogmap" title="地图查看">
    <div id="container"></div>
</el-dialog>
<div>
	<div class="header row">
		<div class="col-lg-2 col-md-0">&nbsp;</div>
		<div class="col-lg-10 col-md-12">
			<img class="icon-logo" src="/pc_static/logo.png" />
		</div>
	</div>
	<div class="card-container" v-if="bgsx?.id && Object.keys(formData).length">
		<el-card style="width: 100%; max-width: 1200px;">
			<template #header>
			  <div v-if="bgsx?.formname" style="text-align:center;"><h3>{{bgsx?.formname}}</h3></div>
			</template>
			<el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules" label-position="top" style="padding:10px">
				<template v-for="field in columns" :key="field.prop">
					<!-- 动态表单项 -->
					<el-form-item v-if="bgsx.kfcx?.includes(field.prop) && checkVisibility(field.prop)" :label="field.label" :prop="field.prop" style="width:100%;">
							<!-- 下拉选择 -->
							<template v-if="['select', 'muselect'].includes(field.type)">
								<el-select v-model="formData[field.prop]" :multiple="field.type === 'muselect'" v-bind="getComponentProps(field)">
									<el-option v-for="opt in field.options" :key="opt.value" :label="opt.label"
										:value="opt.value" />
								</el-select>
							</template>
			
							<!-- 单选框组 -->
							<template v-else-if="field.type === 'radio'">
								<el-radio-group v-model="formData[field.prop]" v-bind="getComponentProps(field)">
									<el-radio v-for="opt in field.options" :key="opt.value" :label="opt.value">
										{{ opt.label }}
									</el-radio>
								</el-radio-group>
							</template>
			
							<!-- 多选框组 -->
							<template v-else-if="field.type === 'checkbox'">
								<el-checkbox-group v-model="formData[field.prop]" v-bind="getComponentProps(field)">
									<el-checkbox v-for="opt in field.options" :key="opt.value" :label="opt.value">
										{{ opt.label }}
									</el-checkbox>
								</el-checkbox-group>
							</template>
			
							<!-- 日期选择 -->
							<template v-else-if="field.type === 'date'">
								<el-date-picker v-model="formData[field.prop]" v-bind="getComponentProps(field)" />
							</template>
			
							<!-- 日期时间选择 -->
							<template v-else-if="field.type === 'datetime'">
								<el-date-picker v-model="formData[field.prop]" v-bind="getComponentProps(field)" />
							</template>
							
                            <!-- 随机密钥、行内计算、字符拼接 -->
                            <template v-else-if="['randomkey','rowcalc', 'stringconcat'].includes(field.type)">
                            	<el-input v-model="formData[field.prop]" v-bind="getComponentProps(field)"></el-input>
                            </template>
			
							<!-- 身份证输入（带扫描按钮） -->
							<template v-else-if="field.type === 'idcard'">
								<el-input v-model="formData[field.prop]" @input="(v) => handleIdCardInput(v, field.prop)" :maxlength="18" show-word-limit v-bind="getComponentProps(field)">
									<template #append>
										<el-button @click="scanIdCard(field.prop)">
											<el-icon>
												<Camera />
											</el-icon>
										</el-button>
									</template>
								</el-input>
							</template>
			
							<!-- 数字输入 -->
							<template v-else-if="field.type === 'number'">
								<el-input v-model="formData[field.prop]" v-bind="getComponentProps(field)" />
							</template>
			
							<!-- 多行文本 -->
							<template v-else-if="field.type === 'textarea'">
								<el-input v-model="formData[field.prop]" v-bind="getComponentProps(field)" />
							</template>
							
                            <!-- 富文本 -->
                            <template v-else-if="field.type === 'richtext'">
                            	<uniedit v-model="formData[field.prop]" v-bind="getComponentProps(field)" />
                            </template>
							
                            <!--联动下拉-->
                            <template v-else-if="field.type === 'linkselect'">
                            	<el-select v-model="formData[field.prop]" @visible-change="handleVisibleChange($event, field.prop)" @change="lxChange(field.prop)" clearable :placeholder="field.placeholder">
                            		<el-option v-for="option in ldoptions[field.prop]" :key="option" :label="option" :value="option"></el-option>
                            	</el-select>
                            </template>
                            
                            <!--省市县联动-->
                            <template v-else-if="field.type == 'area'">
                                <el-cascader style="width:100%;" filterable v-model="formData[field.prop]" :options="regionData" clearable :props="{value: 'label',label: 'label'}" :placeholder="field.placeholder" v-bind="getComponentProps(field)"></el-cascader>
                            </template>
			
							<!-- 子表 -->
							<template v-else-if="field.type === 'subtable'">
								<el-table v-if="formData[field.prop] && Array.isArray(formData[field.prop])" :data="formData[field.prop]" border table-layout="auto" :header-cell-style="{'font-size': '14px', background: '#f9f9f9'}" style="width:100%;">
									<el-table-column v-for="(col, index) in field.zboptions" :key="index" :prop="col.key" :label="col.key" min-width="160px">
										<template #default="scope">
											<template v-if="col.lx && formData[field.prop][scope.$index]">
												<el-input v-if="col.lx === 'text'" v-model="formData[field.prop][scope.$index][col.key]" clearable :placeholder="col.key" style="width:100%"></el-input>
			
												<el-input v-else-if="col.lx === 'textarea'" type="textarea" autosize v-model="formData[field.prop][scope.$index][col.key]" :placeholder="col.key" style="width:100%"></el-input>
			
												<el-input v-else-if="col.lx === 'number'" v-model="formData[field.prop][scope.$index][col.key]" type="number" clearable :placeholder="col.key" style="width:100%"></el-input>
			
												<el-select v-else-if="col.lx === 'select'" v-model="formData[field.prop][scope.$index][col.key]"  clearable filterable :placeholder="col.key" style="min-width:200px;">
													<el-option v-for="option in col.xx.split('/')" :key="option" :label="option" :value="option"></el-option>
												</el-select>
			
												<el-date-picker v-else-if="col.lx == 'date' || col.lx == 'datetime'" v-model="formData[field.prop][scope.$index][col.key]" :type="col.lx" :format="datelx[col.lx].format" :value-format="datelx[col.lx].valueFormat" :placeholder="col.key" style="width:100%"></el-date-picker>
			
												<el-input v-else-if="col.lx === 'mobile'" type="number" min="13000000000" max="19999999999" v-model="formData[field.prop][scope.$index][col.key]" :placeholder="col.key" style="width:100%"></el-input>
			
												<el-input v-else-if="col.lx === 'idcard'" v-model="formData[field.prop][scope.$index][col.key]" :placeholder="col.key" style="width:100%">
												</el-input>
										   </template>
										</template>
									</el-table-column>
									<el-table-column fixed="right" label="操作" width="120">
										<template #default="scope">
										   <el-button link type="danger" @click="DeleteZd(scope.$index, field.prop)">删除</el-button>
										</template>
									</el-table-column>
								</el-table>
								<el-button type="primary" size="small" @click="addRow(field.prop, field.zboptions)">添加一行</el-button>
							</template>
							
							<!-- word模板 -->
							<template v-else-if="field.type === 'word'">
								<a v-if="formData[field.prop]" :href="formData[field.prop]" class="word-link" target="_blank">查看/下载Word</a>
							</template>
							
                            <!--地图定位-->
                            <template v-else-if="field.type == 'map'">
                                <el-input v-model="formData[field.prop]" disabled :placeholder="field.placeholder"></el-input>
                                <el-button v-if="formData[field.prop]" @click="showMyMap(formData[field.prop])">查看</el-button>
                                <el-button v-else @click="getLocation(field.prop, formData)">获取位置</el-button>
                            </template>
			
							<!-- 上传类型处理 -->
							<template v-else-if="['image', 'multiimage', 'sczs'].includes(field.type)">
								<el-upload :file-list="getFileList(field)" v-bind="getComponentProps(field)" :before-upload="(file)=>handleBeforeUpload(file, field)" :on-success="(res)=>handleUploadSuccess(res, field)" :on-remove="(file)=>handleRemove(file, field)"><el-icon><Plus /></el-icon>
								</el-upload>
							</template>
							
                            <!-- 附件上传单独传参 -->
                            <div v-else-if="['file', 'multifile', 'video'].includes(field.type)">
                                <el-button type="success" plain @click="showUploadDialog[field.prop] = true"><el-icon><Upload /></el-icon>上传文件</el-button>&nbsp;
                                <div>
                                    <template v-if="formData[field.prop]">
                                        <div v-if="field.type === 'file'" class="attachment-item">
                                            <span class="file-name2">{{ getFileName(formData[field.prop]) }}</span>
                                            <el-icon class="delete-icon" @click="handleRemove(formData[field.prop],field)"><Close /></el-icon>
                                        </div>
                                        <template v-else>
                                            <div v-for="(url, index) in formData[field.prop]" :key="index" class="attachment-item">
                                                <span class="file-name2">{{ getFileName(url) }}</span>
                                                <el-icon class="delete-icon" @click="handleRemove(index, field)"><Close /></el-icon>
                                            </div>
                                        </template>
                                    </template>
                                </div>
                                <UploadDialog v-model="showUploadDialog[field.prop]" :current-path="getpath()" @success="(url) => handleUploadSuccess(url, field)"/>
                            </div>
			
							<!-- 默认文本输入 -->
							<template v-else>
								<el-input v-model="formData[field.prop]" v-bind="getComponentProps(field)" />
							</template>
					</el-form-item>
				</template>
				
				<template v-if="bgsx.isReservation">
					<!-- 日期选择区块 -->
					<div class="reservation-section">
						<div class="section-header">
							<el-icon>
								<Calendar />
							</el-icon>
							<span class="title">选择预约日期</span>
							<el-tooltip content="请选择可预约日期，灰色日期表示已约满或已预约" placement="right">
								<el-icon class="tip-icon">
									<Warning />
								</el-icon>
							</el-tooltip>
						</div>
						<el-row :gutter="16" class="grid-container">
							<el-col v-for="(date, index) in availableDates" :key="index" :xs="12" :sm="8" :md="6" :lg="6">
								<div class="reservation-card" :class="{'active': formData.reservation_date === date.date, 'disabled': date.remaining <= 0 || date.hasBooked}" @click="selectDate(date)">
									<div class="card-content">
										<div class="main-info">
											<div class="date">{{ date.display }}</div>
											<div class="week">{{ date.week }}</div>
										</div>
										<div class="status-indicator">
											<el-tag :type="date.remaining > 0 ? 'success' : 'danger'" effect="dark" size="small">
												{{ date.remaining > 0 ? '余'+date.remaining : '已满' }}
											</el-tag>
										</div>
									</div>
								</div>
							</el-col>
						</el-row>
					</div>

					<!-- 时段选择区块 -->
					<div class="reservation-section">
						<div class="section-header">
							<el-icon>
								<Clock />
							</el-icon>
							<span class="title">选择预约时段</span>
							<el-tooltip content="灰色时段表示已约满或已预约，请选择可用时段" placement="right">
								<el-icon class="tip-icon">
									<Warning />
								</el-icon>
							</el-tooltip>
						</div>
						<el-row :gutter="16" class="grid-container">
							<el-col v-for="(slot, index) in availableSlots" :key="index" :xs="12" :sm="8" :md="6" :lg="6">
								<div class="reservation-card time-slot" :class="{ 'active': formData.slot_start === slot.start, 'disabled': slot.remaining <= 0 }" @click="selectSlot(slot)">
									<div class="card-content">
										<div class="main-info">
											<div class="time-range">{{ slot.start }} - {{ slot.end }}</div>
								            <!-- <div class="duration">时长 {{ slot.duration }}分钟</div> -->
										</div>
										<div class="status-indicator">
											<el-tag :type="slot.remaining > 0 ? 'success' : 'danger'" effect="dark" size="small">
												{{ slot.remaining > 0 ? '余'+slot.remaining+'人' : '已满' }}
											</el-tag>
										</div>
									</div>
									<el-radio v-model="formData.slot_start" :label="slot.start" style="display: none" />
								</div>
							</el-col>
						</el-row>
					</div>
				</template>

				<el-row justify="center">
					<el-col :span="8" style="text-align: center;margin: 20px;">
						<el-button type="primary" :disabled="isbutton" size="large" style="margin-right:20px" @click="submitForm">确认</el-button>
						<el-button @click="toback" size="large">返回首页</el-button>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
	</div>
	<div style="height:80px"></div>
</div>
`
}